<?php
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

class UsersController extends AppController {

    var $name = 'Users';

    function send() {
        App::import('Vendor', 'ClassPhpmailer', array('file' => 'phpmailer/class.phpmailer.php'));
       // $this->layout = "ajax";
        if (empty($this->data)) {
            
        } else {
            $this->User->recursive = 0;
            if ($users = $this->User->find('all', array('conditions' => array('User.email' => $this->data['User']['correo']), 'fields' => array('User.email', 'User.username', 'User.nombre', 'User.primer_apellido', 'User.segundo_apellido', 'User.id')))) {
                foreach ($users as $user) {
                    $this->User->create();
                    $this->User->id = $user['User']['id'];

                    //Generamos la nueva clave de forma aleatorea

                    $str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
                    $clave = "";
                    for ($i = 0; $i < 8; $i++) {
                        $clave .= substr($str, rand(0, 62), 1);
                    }

                    $this->request->data['User']['password'] = $this->Auth->password($clave);
                    if ($this->User->save($this->data)) {
                        $mail = new PHPMailer();

//Luego tenemos que iniciar la validación por SMTP: 
                        $mail->IsSMTP();
                        $mail->SMTPAuth = true;
                        $mail->Host = "ssl://smtp.gmail.com"; // SMTP a utilizar. Por ej. smtp.elserver.com 
                        $mail->Username = "mabelbra@gmail.com"; // Correo completo a utilizar 
                        $mail->Password = "rocy1234"; // Contraseña 
                        $mail->Port = 465; // Puerto a utilizar 
//Con estas pocas líneas iniciamos una conexión con el SMTP. Lo que ahora deberíamos hacer, es configurar el mensaje a enviar, el //From, etc. 
                        $mail->From = "mabelbra@gmail.com"; // Desde donde enviamos (Para mostrar) 
                        $mail->FromName = "Soporte aplicativo INCODER-PBA  ";

//Estas dos líneas, cumplirían la función de encabezado (En mail() usado de esta forma: “From: Nombre <correo@dominio.com>”) de //correo. 
//$mail->AddAddress('wilavel@gmail.com');// Esta es la dirección a donde enviamos 
                        $mail->AddAddress($user['User']['email']);
                        $mail->IsHTML(true);
//$mail->IsHTML(true); // El correo se envía como HTML 
                        $mail->Subject = "Cambio de clave aplicativo INCODER-PBA"; // Este es el titulo del email. 
                        $body = "Se ha cambiado exitosamente su clave,los datos de su cuenta son: <br>";
                        $body .= " <strong>Usuario: " . $user['User']['nombre'] . " " . $user['User']['primer_apellido'] . $user['User']['segundo_apellido'] . "</strong><br>";
                        $body .= " <strong>Username: " . $user['User']['username'] . "</strong><br>";
                        $body .= " <strong>Nueva Clave: " . $clave . "</strong><br>";
                        $mail->Body = $body; // Mensaje a enviar 
//$mail->SMTPDebug = 1;

                        $exito = $mail->Send(); // Envía el correo. 
//También podríamos agregar simples verificaciones para saber si se envió: 
                        if ($exito) {
                            $this->Session->setFlash("Sus datos fueron envados al correo  " . $user['User']['email']);
                        } else {
                            $this->Session->setFlash("Error :  " . $user['User']['email'] . " " . $mail->ErrorInfo);
                        }
                        $this->redirect(array('controller' => 'Users', 'action' => "send"));
                    } else {
                        $this->Session->setFlash("Error Guardando Datos");
                    }
                }
            } else {
                $this->Session->setFlash("No existe un usuario asociado a este correo");
            }
        }
    }

    function login() {
        $this->pageTitle = 'Inicio';
        $this->layout = "login";
        $this->User->recursive=-1;       
        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                $this->redirect($this->Auth->redirect());
            } else {
                $this->Session->setFlash('Su usuario o contraseña no son correctos.');
            }
        }
    }

    function admin_login() {
        $this->layout = "login";

        if ($this->request->is('post')) {
            if ($this->Auth->login()) {
                //$this->Auth->loginRedirect = array('controller' => 'pages', 'action' => 'admin_index');
                $this->redirect(array('controller' => 'pages', 'action' => 'admin_index'));
            } else {
                $this->Session->setFlash('Su usuario o contraseña no son correctos.', 'flash_custom');
            }
        }
    }

    function logout() {
        $this->Session->setFlash('Su sesión ha expirado.');
        $this->Session->destroy();
        $this->redirect($this->Auth->logout());
    }

    

    function index() {
       
       // $this->User->recursive = 0;
        $this->set('User', $this->User->find('all', array('fields' => array('User.username', 'User.id', 'User.email', 'User.primer_apellido', 'User.nombre', 'Group.name'))));
    }

    function edit($id = null) {

        if (empty($this->data)) {
            $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
            $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
            $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
        } else {
            if ($this->User->save($this->data)) {

                $this->Session->setFlash("Usuario editado con exito", 'flash_custom');
                $this->redirect(array('controller' => 'users', 'action' => "index"));
            } else {
                $this->Session->setFlash("Error Guardando Datos", 'flash_custom');
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            }
        }
    }

    function edit_user() {
        $this->layout = "ajax";
        if (empty($this->data)) {
            $id = $this->Auth->user('id');
            $this->data = $this->User->find("first", array("conditions" => array("User.id" => $id)));
        } else {
            if ($this->Auth->password($this->data['User']['password']) != $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                echo "<script>alert('Las contraseñas no coinciden')</script>";
            } else {
                $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
                if ($this->User->save($this->data)) {

                    $this->Session->setFlash("Usuario editado con exito", 'flash_custom');
                    $this->redirect(array('controller' => 'Pages', 'action' => "display"));
                } else {
                    $this->Session->setFlash("Error Guardando Datos", 'flash_custom');
                }
            }
        }
    }

    function add() {
        $this->layout = "ajax";
        if (!empty($this->data)) {

            if ($this->Auth->password($this->data['User']['password']) != $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                echo "<script>alert('Las contraseñas no coinciden')</script>";
            } else {
                $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
                if ($this->User->saveAll($this->data)) {
                    $this->Session->setFlash("Usuario creado con exito", 'flash_custom');
                    $this->redirect(array("controller" => 'users', 'action' => 'index'));
                } else {
                    $this->Session->setFlash("Error guardando datos", 'flash_custom');
                    $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
                    $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
                }
            }
        } else {

            $this->set('branches', $this->User->Branch->find('list', array('order' => 'nombre ASC', 'fields' => array('id', 'nombre'))));
            $this->set('groups', $this->User->Group->find('list', array('order' => 'name ASC')));
        }
    }

    function delete($id) {

        if ($this->User->delete($id)) {
            $this->Session->setFlash('Usuario Borrado con exito', 'flash_custom');
            $this->redirect(array('controller' => 'Users', 'action' => 'index'));
        }
    }

    function add_users() {
        $this->layout = "ajax";
        if (!empty($this->data)) {
            if ($this->Auth->password($this->data['User']['password']) == $this->Auth->password($this->data['User']['password_confirm'])) {
                $this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
                if ($this->User->save($this->request->data)) {
                    $this->Session->setFlash("Usuario creado con éxito", "flash_custom");
                    $this->redirect(array("controller" => 'Users', 'action' => 'list_users'));
                } else {
                    $this->Session->setFlash(__('El usuario no se pudo guardar, por favor intentelo de nuevo.'), 'flash_custom');
                    $group_id = $this->Auth->user('group_id');
                    if ($group_id == 13) {
                        $this->set('groups', $this->User->Group->find('list', array('conditions' => array('id' => array(13, 19, 20)))));
                        $this->set('mostrar_regionales', false);
                    } else {
                        $this->set('groups', $this->User->Group->find('list'));
                        $this->set('branches', $this->User->Branch->find('list', array('fields' => array('Branch.id', 'Branch.nombre'))));
                        $this->set('mostrar_regionales', true);
                    }
                }
            } else {
                
            }
        } else {
            $group_id = $this->Auth->user('group_id');
            if ($group_id == 134) {
                $this->set('groups', $this->User->Group->find('list', array('conditions' => array('id' => array(13, 19, 20)))));
                $this->set('mostrar_regionales', false);
            } else {
                $this->set('groups', $this->User->Group->find('list'));
                $this->set('branches', $this->User->Branch->find('list', array('fields' => array('Branch.id', 'Branch.nombre'))));
                $this->set('mostrar_regionales', true);
            }
        }
    }

   
    
}


?>